package com.chm.fw.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.ImageView;

import com.chm.framwork.utilcode.util.ImageUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class CameraUtils {

    /**
     * 打开相册
     *
     * @param requestcode 响应码
     * @param activity    上下文
     */
    public static void toTakePicture(int requestcode, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        activity.startActivityForResult(intent, requestcode);
    }

    /**
     * 拍照打开照相机！
     *
     * @param requestcode 返回值
     * @param activity    上下文
     * @param fileName    生成的图片文件的路径
     * @param imgName     图片文件名
     */
    public static void toTakePhoto(int requestcode, Activity activity, File fileName, String imgName, String authority) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra("camerasensortype", 2);// 调用前置摄像头
        intent.putExtra("autofocus", true);// 自动对焦
        intent.putExtra("fullScreen", false);// 全屏
        intent.putExtra("showActionIcons", false);
        try {
            //如果这个文件不存在就创建一个文件夹
            if ((!fileName.exists()) && fileName.mkdirs()) {
                Log.d("TAG", "创建文件夹");
            }
            Uri imageUri = Uri.fromFile(new File(fileName, imgName));
            if (Build.VERSION.SDK_INT >= 24) { //通过FileProvider创建一个content类型的Uri
                imageUri = FileProvider.getUriForFile(activity, authority, new File(fileName, imgName));
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            activity.startActivityForResult(intent, requestcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片显示到ImageView（缩小到ImageView控件的大小）（如果获取拍摄的照片，该方法在onActivityResult方法中使用）
     *
     * @param png_quality 压缩图片质量（0-100）
     */
    public static void setPic2ImageView(ImageView imageView, File file_img, int png_quality) {
        int width = imageView.getWidth();
        int height = imageView.getHeight();

        BitmapFactory.Options factoryOptions = new BitmapFactory.Options();

        factoryOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file_img.getPath(), factoryOptions);

        // 照片的原来大小
        int imageWidth = factoryOptions.outWidth;
        int imageHeight = factoryOptions.outHeight;

        // 图片缩小的比例
        int scaleFactor = Math.min(imageWidth / width, imageHeight / height);

        // Decode the image file into a Bitmap sized to fill the View
        factoryOptions.inJustDecodeBounds = false;
        factoryOptions.inSampleSize = scaleFactor;
        factoryOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(file_img.getPath(), factoryOptions);
        bitmap.compress(Bitmap.CompressFormat.PNG, png_quality, new ByteArrayOutputStream());// (0-100)压缩文件
        // 缩小后图片的大小（KB）
        //int byteCount = bitmap.getByteCount()/1024;
        imageView.setImageBitmap(bitmap);
        //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    /**
     * 裁剪图片（手指滑动截图框的大小）
     * uri : content://com.jtb.zdgj_app.test.fileprovider/download/zdgj_app_imgs/avatar.png
     * uri : content://com.android.providers.media.documents/document/image%3A123851
     * uriTempFile : Uri uriTempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/00CHM/" + fileName);
     */
    public static void startPhotoZoom(int requestCode, Uri uri, Uri uriTempFile, Activity activity) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用系统自带的图片裁剪
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//设置在开启的Intent中设置显示的VIEW可裁剪
        //宽高比
        if (android.os.Build.BRAND.contains("HUAWEI")) {//华为特殊处理 不然会显示圆
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        //裁剪图片宽高
        intent.putExtra("outputX", 350);
        intent.putExtra("outputY", 350);
        intent.putExtra("return-data", true);//return置为false，获取截图保存的uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriTempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true);//取消人脸识别功能
        activity.startActivityForResult(intent, requestCode);
    }

    //图片压缩
    public static void saveBitmap(Bitmap file, String outPath) {
        //像素压缩
        Bitmap bitmap = ImageUtils.compressByScale(file, 1024, 1024);
        //质量压缩
        bitmap = ImageUtils.compressByQuality(bitmap, 60);
        //保存图片
        ImageUtils.save(bitmap, outPath, Bitmap.CompressFormat.PNG);
    }
}
